package main

import (
	"fmt"
	"log"
	"mime/multipart"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
)

func main() {
	router := gin.Default()
	// 为 multipart forms 设置较低的内存限制 (默认是 32 MiB)
	// router.MaxMultipartMemory = 8 << 20  // 8 MiB
	router.POST("/upload", func(c *gin.Context) {

		// weekFile := excelize.NewFile()
		// styleOne, styleTwo, _, _ := excelStyle(weekFile)
		// weekFile.SetSheetName("Sheet1", "上周工作内容")
		// weekFile.SetColWidth("上周工作内容", "A", "A", 17.38)
		// weekFile.SetColWidth("上周工作内容", "B", "B", 9.38)
		// weekFile.SetColWidth("上周工作内容", "C", "C", 69.38)
		// weekFile.SetColWidth("上周工作内容", "D", "E", 12.38)
		// weekFile.SetColWidth("上周工作内容", "F", "F", 19.38)
		// weekFile.SetColWidth("上周工作内容", "G", "G", 6.38)
		// weekFile.SetColWidth("上周工作内容", "H", "H", 9.38)
		// weekFile.SetColWidth("上周工作内容", "I", "I", 22.38)
		// weekFile.MergeCell("上周工作内容", "A1", "I1")

		// weekFile.SetCellStyle("上周工作内容", "A1", "I1", styleOne)
		// weekFile.SetSheetRow("上周工作内容", "A1", &[]interface{}{"上周已经完成的任务总结"})
		// weekFile.SetSheetRow("上周工作内容", "A2", &[]interface{}{"需求/任务编号", "任务类型", "任务名称", "实际开始日期", "实际结束日期", "实际工作量（人/天）", "责任人", "完成比率", "任务拖延原因/客户评价"})
		// weekFile.SetCellStyle("上周工作内容", "A2", "I2", styleTwo)
		weekFile := initFile()
		form, _ := c.MultipartForm()
		files := form.File["files"]
		//初始化 内容初始行
		z := 3
		//获取当前周
		thisWeek := GetMondayToFirday()
		//作者
		var people string
		for _, file := range files {
			dst := "D:/" + file.Filename
			// 上传文件至指定目录
			c.SaveUploadedFile(file, dst)
			people = doFile(file, weekFile, dst, &z, thisWeek)
		}
		// 单文件
		//file, _ := c.FormFile("file")
		// log.Println(file.Filename)
		// dst := "D:/" + file.Filename
		// // 上传文件至指定目录
		// c.SaveUploadedFile(file, dst)

		// f, err := excelize.OpenFile(dst)
		// if err != nil {
		// 	log.Fatal("文件读取失败")
		// }
		// defer os.Remove(dst)
		// defer func() {
		// 	if err := f.Close(); err != nil {
		// 		log.Fatal(err)
		// 	}
		// }()
		// //拆分文件名称
		// name := strings.Split(file.Filename, "-")
		// //年
		// year := name[1][0:4]

		// //月
		// month := name[1][4:6]

		// //姓名
		// people := name[2][0:strings.Index(name[2], ".")]

		// //获取当前周
		// thisWeek := GetMondayToFirday()
		// z := 3
		// for i := 0; i < len(thisWeek); i++ {

		// 	week := strings.Split(thisWeek[i], "-")
		// 	if strings.EqualFold(week[0], year) && strings.EqualFold(week[1], month) {
		// 		rows, err := f.GetRows(week[2])
		// 		if err != nil {
		// 			log.Fatal(err)
		// 		}

		// 		for j := 1; j < len(rows); j++ {
		// 			row := rows[j]
		// 			startAndEndTime := year + "/" + month + "/" + week[2]
		// 			workload, _ := strconv.ParseFloat(row[5], 64)
		// 			workload = workload / 8
		// 			weekFile.SetSheetRow("上周工作内容", "A"+strconv.Itoa(z), &[]interface{}{row[6], row[2], row[3], startAndEndTime, startAndEndTime, workload, people})
		// 			weekFile.SetCellStyle("上周工作内容", "A"+strconv.Itoa(z), "I"+strconv.Itoa(z), styleThree)
		// 			weekFile.SetCellStyle("上周工作内容", "C"+strconv.Itoa(z), "C"+strconv.Itoa(z), styleFour)
		// 			z++
		// 		}
		// 	}
		// }
		friday := strings.Replace(GetWeek(time.Now(), 4), "-", "", -1)

		weekFileName := people + "周报" + friday
		//weekFile.SaveAs("D:/" + weekFileName)
		buffer, _ := weekFile.WriteToBuffer()
		//设置文件名称
		c.Header("Content-Disposition", "attachment; filename="+url.QueryEscape(weekFileName))
		//设置文件类型
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, x-token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PATCH, PUT")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type,Content-Disposition")
		c.Header("Access-Control-Allow-Credentials", "true")
		c.Header("response-type", "blob")

		_, _ = c.Writer.Write(buffer.Bytes())
		c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", weekFileName))
	})
	router.Run(":8990")

}

// 获取本周知道周几的日期 w 为星期数   0-周一   1-周二  ...
func GetWeek(t time.Time, w int) string {
	offset := int(time.Monday - t.Weekday())
	if offset > 0 {
		offset = -6
	}
	monday := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset+w)
	return monday.Format("2006-01-02")
}

// 获取当前周一到周五的日期    ["2022-11-28","2022-11-29","2022-11-30","2022-12-01","2022-12-02"]
func GetMondayToFirday() [5]string {
	var week [5]string
	for i := 0; i < len(week); i++ {
		week[i] = GetWeek(time.Now(), i)
	}
	return week

}

// 对传入的文件进行处理
func doFile(file *multipart.FileHeader, weekFile *excelize.File, dst string, z *int, thisWeek [5]string) string {
	f, err := excelize.OpenFile(dst)
	if err != nil {
		log.Fatal("文件读取失败")
	}
	defer os.Remove(dst)
	defer func() {
		if err := f.Close(); err != nil {
			log.Fatal(err)
		}
	}()
	//拆分文件名称
	name := strings.Split(file.Filename, "-")
	//年
	year := name[1][0:4]

	//月
	month := name[1][4:6]

	//姓名
	people := name[2][0:strings.Index(name[2], ".")]
	_, _, styleThree, styleFour := excelStyle(weekFile)
	for i := 0; i < len(thisWeek); i++ {

		week := strings.Split(thisWeek[i], "-")
		if strings.EqualFold(week[0], year) && strings.EqualFold(week[1], month) {
			rows, err := f.GetRows(week[2])
			if err != nil {
				log.Fatal(err)
			}

			for j := 1; j < len(rows); j++ {
				row := rows[j]
				if len(row) == 0 {
					continue
				}
				startAndEndTime := year + "/" + month + "/" + week[2]
				workload, _ := strconv.ParseFloat(row[5], 64)
				workload = workload / 8
				weekFile.SetSheetRow("上周工作内容", "A"+strconv.Itoa(*z), &[]interface{}{row[6], row[2], row[3], startAndEndTime, startAndEndTime, workload, people})
				weekFile.SetCellStyle("上周工作内容", "A"+strconv.Itoa(*z), "I"+strconv.Itoa(*z), styleThree)
				weekFile.SetCellStyle("上周工作内容", "C"+strconv.Itoa(*z), "C"+strconv.Itoa(*z), styleFour)
				*z++
			}

		}
	}
	return people
}

// excel 样式
func excelStyle(weekFile *excelize.File) (int, int, int, int) {
	styleOne, _ := weekFile.NewStyle(&excelize.Style{
		Border: []excelize.Border{
			{Type: "left", Color: "000000", Style: 1},
			{Type: "top", Color: "000000", Style: 1},
			{Type: "bottom", Color: "000000", Style: 1},
			{Type: "right", Color: "000000", Style: 1},
		},
		Fill: excelize.Fill{
			Type:    "pattern",
			Color:   []string{"#c0c0c0"},
			Pattern: 1,
		},
		Alignment: &excelize.Alignment{
			Horizontal: "center",
			Vertical:   "center",
			WrapText:   true,
		},
		Font: &excelize.Font{
			Family: "宋体",
			Bold:   true,
			Size:   10,
			Color:  "000000",
		},
	})
	styleTwo, _ := weekFile.NewStyle(&excelize.Style{
		Border: []excelize.Border{
			{Type: "left", Color: "000000", Style: 1},
			{Type: "top", Color: "000000", Style: 1},
			{Type: "bottom", Color: "000000", Style: 1},
			{Type: "right", Color: "000000", Style: 1},
		},
		Fill: excelize.Fill{
			Type:    "pattern",
			Color:   []string{"#ffff99"},
			Pattern: 1,
		},
		Alignment: &excelize.Alignment{
			Horizontal: "center",
			Vertical:   "center",
			WrapText:   true,
		},
		Font: &excelize.Font{
			Family: "宋体",
			Bold:   true,
			Size:   10,
			Color:  "000000",
		},
	})
	styleThree, _ := weekFile.NewStyle(&excelize.Style{
		Border: []excelize.Border{
			{Type: "left", Color: "000000", Style: 1},
			{Type: "top", Color: "000000", Style: 1},
			{Type: "bottom", Color: "000000", Style: 1},
			{Type: "right", Color: "000000", Style: 1},
		},
		Alignment: &excelize.Alignment{
			Horizontal: "center",
			Vertical:   "center",
			WrapText:   true,
		},
		Font: &excelize.Font{
			Family: "宋体",
			Size:   10,
			Color:  "000000",
		},
	})
	styleFour, _ := weekFile.NewStyle(&excelize.Style{
		Border: []excelize.Border{
			{Type: "left", Color: "000000", Style: 1},
			{Type: "top", Color: "000000", Style: 1},
			{Type: "bottom", Color: "000000", Style: 1},
			{Type: "right", Color: "000000", Style: 1},
		},
		Alignment: &excelize.Alignment{
			Horizontal: "left",
			Vertical:   "center",
			WrapText:   true,
		},
		Font: &excelize.Font{
			Family: "宋体",
			Size:   10,
			Color:  "000000",
		},
	})
	return styleOne, styleTwo, styleThree, styleFour
}

// 生成文件初始化(周报初始化)
func initFile() *excelize.File {
	weekFile := excelize.NewFile()
	styleOne, styleTwo, _, _ := excelStyle(weekFile)
	weekFile.SetSheetName("Sheet1", "上周工作内容")
	weekFile.SetColWidth("上周工作内容", "A", "A", 17.38)
	weekFile.SetColWidth("上周工作内容", "B", "B", 9.38)
	weekFile.SetColWidth("上周工作内容", "C", "C", 69.38)
	weekFile.SetColWidth("上周工作内容", "D", "E", 12.38)
	weekFile.SetColWidth("上周工作内容", "F", "F", 19.38)
	weekFile.SetColWidth("上周工作内容", "G", "G", 6.38)
	weekFile.SetColWidth("上周工作内容", "H", "H", 9.38)
	weekFile.SetColWidth("上周工作内容", "I", "I", 22.38)
	weekFile.MergeCell("上周工作内容", "A1", "I1")

	weekFile.SetCellStyle("上周工作内容", "A1", "I1", styleOne)
	weekFile.SetSheetRow("上周工作内容", "A1", &[]interface{}{"上周已经完成的任务总结"})
	weekFile.SetSheetRow("上周工作内容", "A2", &[]interface{}{"需求/任务编号", "任务类型", "任务名称", "实际开始日期", "实际结束日期", "实际工作量（人/天）", "责任人", "完成比率", "任务拖延原因/客户评价"})
	weekFile.SetCellStyle("上周工作内容", "A2", "I2", styleTwo)
	return weekFile
}
